<extend name="Public/base"/>
<block name="style">
    <link rel="stylesheet" href="__STATIC__/styles/video_view.css">
    <link rel="stylesheet" href="__STATIC__/styles/vendors/video.min.css">
    <link rel="stylesheet" href="__STATIC__/styles/vendors/bootstrap-table.css">
    <link rel="stylesheet" href="__STATIC__/styles/vendors/bootstrap-select.min.css">
    <link rel="stylesheet" href="__STATIC__/styles/vendors/bootstrap-datetimepicker.min.css">
    <style>
        .bs-bars{
            width:80%;
        }
        .during{
            display: inline-block;
            width: 150px;   
            line-height: 34px;
        }
        .pull-right.search input, #search.form-control, #search .form-control {
            width: 140px;
        }
        button#remove ,button#searchAll{
            margin-right: 10px;
        }
    </style>
</block>
<block name="content">
    <div class="bs-example bs-example-tabs nav-tabs-custom" data-example-id="togglable-tabs">
        <ul id="myTabs" class="nav nav-tabs" role="tablist">
            <li role="presentation" class="active"><a href="#home" id="home-tab" role="tab" data-toggle="tab" aria-controls="home" aria-expanded="true">回传历史</a></li>
            <li role="presentation" class=""><a href="#profile" role="tab" id="profile-tab" data-toggle="tab" aria-controls="profile" aria-expanded="false">监控</a></li>
        </ul>
        <div id="myTabContent" class="tab-content">
            <div role="tabpanel" class="tab-pane fade active in" id="home" aria-labelledby="home-tab">
                <div id="toolbar">

<!-- <div class="panel panel-default"> -->
    <!-- <div class="panel-body"> -->
                            <form role="form" class="form-inline">             
                    <button id="remove" class="btn btn-danger btn-flat" disabled>
                        <i class="glyphicon glyphicon-remove"></i>删除
                    </button>
                    <!--<select class="selectpicker">-->
                        <!--<option>所有回传人</option>-->
                    <!--</select>-->
                    <select name="is_open" id="is_open" class="selectpicker right pull-right">
                        <option value="-1">全部</option>
                        <option value="1">已开放</option>
                        <option value="0">未开放</option>
                    </select>
                    <select id ='searchOption' class="selectpicker right pull-right">
                        <option value="1">部门</option>
                        <option value="2">回传人</option>
                    </select>
                    <button type="button" id="searchAll" class="btn btn-info btn-flat query">查看全部</button>
                    <div class="during-left during">
                        <div class='input-group date' id='datetimepicker1'>
                            <input type='text' class="timesearch form-control" name="begin_time"/>
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                            </span>
                        </div>

                    </div>
                    <div class="during-center during" style="text-align: center;width:30px;">
                        至
                    </div>
                    <div class="during-right during">
                        <div class='input-group date' id='datetimepicker2'>
                            <input type='text' class="timesearch form-control" name="end_time"/>
                            <span class="input-group-addon">
                                            <span class="glyphicon glyphicon-calendar"></span>
                                        </span>
                        </div>
                    </div>
                    <button type="button" class="btn btn-info btn-flat query">查询</button>
                            </form>
                        <!-- </div> -->
                    <!-- </div> -->

                </div>

                <table id="table" data-toolbar="#toolbar">
                </table>
            </div>
            <div role="tabpanel" class="tab-pane fade" id="profile" aria-labelledby="profile-tab">
                <div id="monitorToolbar">
                    <button id="removeMonitor" class="btn btn-danger btn-flat" disabled>
                        <i class="glyphicon glyphicon-remove"></i>删除
                    </button>
                    <button id="add" class="btn btn-primary btn-flat">
                        添加监控
                    </button>
                </div>
                <table id="monitorTable" data-toolbar="#monitorToolbar">
                </table>
            </div>
        </div>
    </div>
    <div class="modal fade" id="confirm_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">确认</h4>
                </div>
                <div class="modal-body">
                    确定要删除吗?
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger btn-flat confirmDel">删除</button>
                    <button type="button" class="btn btn-default btn-flat" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="addition_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">备注</h4>
                </div>
                <div class="modal-body">
                    <textarea class="form-control" id="addition"></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-success btn-flat">确定</button>
                    <button type="button" class="btn btn-default btn-flat" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="video-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">播放视频</h4>
                </div>
                <div class="modal-body">
                    <video id="my-video" class="video-js" controls preload="auto" width="768" height="561"
                           poster="//vjs.zencdn.net/v/oceans.png" data-setup="{}">
                        <!--<source src="__STATIC__/video_examples/oceans.mp4" type='video/mp4'>-->
                        <p class="vjs-no-js">
                            查看视频请开启Javascript, 需要升级到
                            <a href="http://videojs.com/html5-video-support/" target="_blank">支持HTML5 视频</a>
                            的浏览器
                        </p>
                    </video>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="monitor-video-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content" style="width: 798px;height: 647px;">
                <div class="modal-header" style="width: 798px;height: 56px;">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">监控视频</h4>
                </div>
                <div class="modal-body" style="width: 798px;height: 591px;">
                    <div id="monitor_obj" width="768" height="561"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="monitor-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form id="monitorForm" action="{:U('addMonitor')}" method="post">
                    <div class="modal-body">
                        <div class="control-group">
                            <label class="control-label" for="video_url">RTSP地址</label>
                            <div class="controls">
                                <input type="text" class="form-control"
                                       id="video_url" name="video_url">
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label" for="title">备注</label>
                            <div class="controls">
                                <input type="text" class="form-control"
                                       id="title" name="title">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-success btn-flat confirmMonitor">确定</button>
                        <button type="button" class="btn btn-default btn-flat" data-dismiss="modal">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</block>

<block name="script">
    <script src="__STATIC__/scripts/vendors/bootstrap-select.min.js"></script>
    <script src="__STATIC__/scripts/vendors/bootstrap-table.js"></script>
    <script src="__STATIC__/scripts/vendors/video.min.js"></script>
    <script src="__STATIC__/scripts/vendors/videojs.ie8.min.js"></script>
    <script src="__STATIC__/scripts/vendors/sortable-jquery.binding.js"></script>
    <script src="__STATIC__/scripts/vendors/Sortable.min.js"></script>
    <script src="__STATIC__/scripts/vendors/videojs-contrib-hls.min.js"></script>
    <script src="__STATIC__/scripts/vendors/moment.min.js"></script>
    <script src="__STATIC__/scripts/vendors/bootstrap-datetimepicker.min.js"></script>
    <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/4.0.2/videojs-contrib-hls.min.js"></script>-->
    <script>
        /**
         * Created by mingtao on 7/22/16.
         */

        var $table = $('#table');
        var $monitorTable = $('#monitorTable');
        var $remove = $('#remove');
        var $removeMonitor = $('#removeMonitor');
        var $videoModal = $('#video-modal');
        var $monitorModal = $('#monitor-modal');
        var $monitorVideoModal = $('#monitor-video-modal');
        var tableHelper;
        var $my_video = videojs('my-video');
        var $confirmModal = $('#confirm_modal');
        var removeMonitor = false;
        var $confirmDel = $('.confirmDel');


        function getVLC(name) {
            if (window.document[name]) {
                return window.document[name];
            }
            if (navigator.appName.indexOf("Microsoft Internet") == -1) {
                if (document.embeds && document.embeds[name])
                    return document.embeds[name];
            } else {
                return document.getElementById(name);
            }
        }

        var vlc = getVLC('vlc');



        var TableHelper = function(){
            var oTableHelper = new Object();

            oTableHelper.selections = [];

            oTableHelper.monitorSelections = [];

            oTableHelper.init = function(){
                $table.bootstrapTable({
                    formatLoadingMessage: function () {
                        return '正在努力地加载数据中，请稍候……';
                    },
                    formatRecordsPerPage: function (pageNumber) {
                        return '每页显示 ' + pageNumber + ' 条记录';
                    },
                    formatShowingRows: function (pageFrom, pageTo, totalRows) {
                        return '显示第 ' + pageFrom + ' 到第 ' + pageTo + ' 条记录，总共 ' + totalRows + ' 条记录';
                    },
                    formatSearch: function () {
                        return '搜索';
                    },
                    formatNoMatches: function () {
                        return '没有找到匹配的记录';
                    },
                    formatPaginationSwitch: function () {
                        return '隐藏/显示分页';
                    },
                    formatRefresh: function () {
                        return '刷新';
                    },
                    formatToggle: function () {
                        return '切换';
                    },
                    formatColumns: function () {
                        return '列';
                    },
                    responseHandler:function(res){
                        return res;
                    },
                    url:"{:U('playbackList')}",
                    method:'get',
                    striped:true,
                    cache:false,
                    pagination:true,
                    sortable:true,
                    sortName:'add_time',
                    sortOrder:'desc',
                    sidePagination:'server',
                    queryParams:oTableHelper.queryParams,
                    pageNumber:1,
                    pageSize:10,
                    pageList:[10,20,50],
                    uniqueId:'playback_id',
                    search:true,
                    height:getHeight(),

                    columns:[
                        {
                            checkbox:true,
                            align:'center'
                        },
                        {
                            field: 'video_url',
                            title: '视频',
                            align: 'center',
                            formatter: function (value) {
                                return '<a href="javascript: void 0" value="'+value+'" class="title glyphicon glyphicon-play-circle" aria-hidden="true"></a>';
                            },
                            events: operateEvents
                        },
                        {
                            field: 'user_name',
                            title: '回传人',
                            align: 'center'
                        },
                        {
                            field: 'org_name',
                            title: '部门',
                            align: 'center'
                        },
                        {
                            field: 'add_time',
                            title: '回传时间',
                            align: 'center',
                            sortable:true,

                        },
                        {
                            field: 'position',
                            title: '地址',
                            align: 'center'
                        },
                        {
                            field:'is_open',
                            title:'操作',
                            formatter:function(value, row){
                                if(value == 0){
                                    return '<button class="btn btn-primary btn-flat video-modify">开放权限</button>';
                                }else{
                                    return '<button class="btn btn-primary btn-flat video-modify">关闭权限</button>';
                                }

                            },
                            align: 'center',
                            events:operateEvents
                        }
                    ]
                });

                $monitorTable.bootstrapTable({
                    formatLoadingMessage: function () {
                        return '正在努力地加载数据中，请稍候……';
                    },
                    formatRecordsPerPage: function (pageNumber) {
                        return '每页显示 ' + pageNumber + ' 条记录';
                    },
                    formatShowingRows: function (pageFrom, pageTo, totalRows) {
                        return '显示第 ' + pageFrom + ' 到第 ' + pageTo + ' 条记录，总共 ' + totalRows + ' 条记录';
                    },
                    formatSearch: function () {
                        return '搜索';
                    },
                    formatNoMatches: function () {
                        return '没有找到匹配的记录';
                    },
                    formatPaginationSwitch: function () {
                        return '隐藏/显示分页';
                    },
                    formatRefresh: function () {
                        return '刷新';
                    },
                    formatToggle: function () {
                        return '切换';
                    },
                    formatColumns: function () {
                        return '列';
                    },
                    responseHandler:function(res){
                        return res;
                    },
                    url:"{:U('monitorList')}",
                    method:'get',
                    striped:true,
                    cache:false,
                    pagination:true,
                    sortable:false,
                    sortOrder:'asc',
                    sidePagination:'server',
                    queryParams:oTableHelper.queryParams,
                    pageNumber:1,
                    pageSize:10,
                    pageList:[10,20,50],
                    uniqueId:'video_monitor_id',
                    search:false,
                    height:getHeight(),

                    columns:[
                        {
                            checkbox:true,
                            align:'center'
                        },
                        {
                            field: 'video_url',
                            title: '视频',
                            align: 'center',
                            formatter: function (value) {
                                return '<a href="javascript: void 0" value="'+value+'" class="monitor_title glyphicon glyphicon-play-circle" aria-hidden="true"></a>';
                            },
                            events: operateEvents
                        },
                        {
                            field: 'title',
                            title: '备注',
                            align: 'center'
                        },
                    ]
                });
//                setTimeout(function () {
//                    $table.bootstrapTable('resetView');
//                }, 2000);

//                $(window).resize(function () {
//                    setTimeout(function () {
//                        $table.bootstrapTable('resetView', {
//                            height: getHeight()
//                        });
//                    }, 100);
//                });
                $(window).resize(function () {
                    $table.bootstrapTable('resetView', {height:getHeight()});
                    $monitorTable.bootstrapTable('resetView', {height:getHeight()});
                });
                $table.on('check.bs.table uncheck.bs.table ' +
                        'check-all.bs.table uncheck-all.bs.table', function () {
                    $('#remove').prop('disabled', !$table.bootstrapTable('getSelections').length);

                    // save your data, here just save the current page
                    oTableHelper.selections = oTableHelper.getIdSelections();
                    // push or splice the selections if you want to save all data selections
                });
                $monitorTable.on('check.bs.table uncheck.bs.table ' +
                        'check-all.bs.table uncheck-all.bs.table', function () {
                    $('#removeMonitor').prop('disabled', !$monitorTable.bootstrapTable('getSelections').length);

                    // save your data, here just save the current page
                    oTableHelper.monitorSelections = oTableHelper.getMonitorIdSelections();
                    // push or splice the selections if you want to save all data selections
                });



                $table.on('expand-row.bs.table', function (e, index, row, $detail) {
                    if (index % 2 == 1) {
                        $detail.html('Loading from ajax request...');
                        $.get('LICENSE', function (res) {
                            $detail.html(res.replace(/\n/g, '<br>'));
                        });
                    }
                });


            };

            oTableHelper.queryParams = function(params){
                var temp = {
                    limit:params.limit,
                    offset:params.offset,
                    search:params.search,
                    sortOrder:this.sortOrder,
                    searchOption:$("#searchOption").val(),
                    is_open:$("#is_open").val(),
                    begin_time:$('input[name=begin_time]').val(),
                    end_time:$('input[name=end_time]').val(),
                };
                return temp;
            };

            oTableHelper.monitorQueryParams = function (params) {
                var temp = {
                    limit: params.limit,
                    offset:params.offset
                };
                return temp;
            };


            oTableHelper.getIdSelections = function(){
                return $.map($table.bootstrapTable('getSelections'), function (row) {
                    return row.playback_id;
                })
            };

            oTableHelper.getMonitorIdSelections = function () {
                return $.map($monitorTable.bootstrapTable('getSelections'), function (row) {
                    return row.video_monitor_id;
                })
            };

            oTableHelper.refresh = function(){
                $table.bootstrapTable('refresh');
            };

            oTableHelper.refreshMonitor = function () {
                $monitorTable.bootstrapTable('refresh');
            };

            return oTableHelper;
        };
        var currentMonitorMrl;

        window.operateEvents = {
            'click .title': function (e, value, row, index) {
                currentMonitorMrl = value;
                $monitorVideoModal.find('.modal-title').text('播放视频');
                $monitorVideoModal.modal('show');

//                $videoModal.modal('show');
//                $my_video.src(
//                    {
//                        src:value,
//                        type:'application/x-mpegURL',
//                        withCredentials:false
//                    }
//                );
//                $my_video.play();
            },
            
            'click .video-modify':function (e, value, row, index) {
                var val = 0;
                if(value == 0){
                    val = 1;
                }
                $.get(
                    "{:U('changeOpen')}",
                    {
                        id:row.playback_id,
                        val:val
                    },
                    function(data){
                        if(data.status == 1){
                            layer.msg('修改权限完毕成功');
                            $table.bootstrapTable('refresh');
                        }else{
                            layer.msg(data.msg);
                        }
                    }
                )
            },
            
            'click .monitor_title': function (e, value, row, index) {
                currentMonitorMrl = value;
                $monitorVideoModal.find('.modal-title').text('监控视频');
                $monitorVideoModal.modal('show');
            },
            'click .addition': function (e, value, row, index) {
                $('#addition').val(value);
                $('#addition_modal').modal('show');
            }
        };

        function getHeight() {
            return $("#right").height() - 25 - $('#myTabs').outerHeight();
        }


        function initValidate(){
            var obj = $('#monitorForm');
            obj.validate({
                debug:true,
                submitHandler:function(form){
                    var url = $(form).prop('action')
                    var postData = $(form).serialize();

                    $.post(url, postData, function(data){
                        if(data.status == 1){
                            tableHelper.refreshMonitor();
                            $('#monitorForm')[0].reset();
                            $monitorModal.modal('hide');
                        }else{
                            layer.msg(data.msg);
                        }

                    });
                },
                rules:{
                    video_url:'required',
                    title:'required'
                },
                messages:{
                    video_url:"RTSP地址不能为空",
                    title:'备注不能为空'
                }
            })
        }


        $(function () {
            initValidate();
            tableHelper = new TableHelper();
            tableHelper.init();

            $('#is_open').on('changed.bs.select', function (e) {
                tableHelper.refresh();
            });
            $('.query').click(function() { tableHelper.refresh();});
            // $('.timesearch').bind('input propertychange', function() {  
            //     tableHelper.refresh();
            // }); 
            // 点击查看全部数据
            $('#searchAll').click(function(){
                // $("#is_open option[value='"+-1+"']").attr('selected',true);
                // $("#is_open").find("option[value='-1']").
                $("button[data-id='is_open']").attr('title','全部');
                $("button[data-id='is_open']").find('.filter-option').html('全部');
                $('#is_open')[0].selectedIndex = 0; 
                $('#is_open')[0].selectedIndex = 0;
                $('input[name=begin_time]').val('');
                $('input[name=end_time]').val('');
                $table.bootstrapTable('destroy');
                tableHelper.init();
            });
            $remove.click(function () {
                $confirmModal.modal('show');
                removeMonitor = false;
            });

            $removeMonitor.click(function () {
                $confirmModal.modal('show');
                removeMonitor = true;
            });

            $videoModal.on('hide.bs.modal', function () {
                $my_video.reset();
            });

            $monitorVideoModal.on('hide.bs.modal', function () {
                $monitorVideoModal.find('#monitor_obj').empty();
            });

            $monitorVideoModal.on('show.bs.modal', function () {
                var value = currentMonitorMrl;
                setTimeout(function () {
                    var html = '<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" codebase="http://download.videolan.org/pub/videolan/vlc/last/win32/axvlc.cab" id="vlc">'+
                        '<embed type="application/x-vlc-plugin" pluginspage="http://www.videolan.org"  name="vlc" width="768" height="561" src="'+ value+'"/>'+
                        '</object>';
                    $monitorVideoModal.find('#monitor_obj').html(html);
                }, 500);

//                $monitorVideoModal.animate({left:'1px'});
//                $monitorVideoModal.animate({right:'1px'});
            });

            $confirmDel.click(function(){
                $confirmModal.modal('hide');
                if(removeMonitor){
                    $.post({
                        url:"{:U('deleteMonitor')}",
                        data:{
                            selectedIds : tableHelper.monitorSelections
                        },
                        success:function(data){
                            if(data.status == 1){
                                layer.msg('删除成功');
                                tableHelper.refreshMonitor();
//                                $table.bootstrapTable('refresh');
                            }else{
                                layer.msg(data.msg);
                            }
                        }
                    });
                }else{
                    $.post({
                        url:"{:U('delete')}",
                        data:{
                            selectedIds : tableHelper.selections
                        },
                        success:function(data){
                            if(data.status == 1){
                                layer.msg('删除成功');
                                tableHelper.refresh();
                            }else{
                                layer.msg(data.msg);
                            }
                        }
                    });
                }
            });

            $('#add').click(function () {
                $monitorModal.modal('show');
                $monitorModal.find('form')[0].reset();
            });


            $(window).resize(function () {
                setTimeout(function () {
                    $table.bootstrapTable('resetView', {
                        height: getHeight()
                    });
                }, 100);
            });
            /**
             * 这是将视频设为可拖动排序的部分
             */
            $('#videos').sortable({
                //排序时动画during 150ms
                animation: 150,
                //只有在‘备注’的区域可以被拖动
                handle: '.addition'
            });

            $('#monitor-add').click(function () {
                $('#monitor-modal').modal('show');
            });

            $('.fixed-table-container').addClass('box box-primary');

            /**
             * 与调整table高度同理，调整tab panel的高度
             * @type {number}
             */
            var height = $(window).height()-$('.navbar').outerHeight() - $('#myTabs').outerHeight()-35-$('.main-footer').outerHeight(true);
            $('#myTabContent').innerHeight(height);
            $(window).on('resize', function () {
                var height = $(window).height()-$('.navbar').outerHeight() - $('#myTabs').outerHeight()-35-$('.main-footer').outerHeight(true);
                $('#myTabContent').innerHeight(height);
            });

            /**
             * 视频备注模态框
             */
            $('.video-box .addition-toggle').click(function () {
                $('#addition_modal').modal('show');
            });

            /**
             * 定制的播放/暂停按钮
             */
            $('.custom-control').click(function () {
                var $this = $(this);
                //通过data-value找到video的index
                var index = $this.attr('data-value');
                /**
                 * 重要，一个页面有多个视频时，若要手动控制视频，需要每个video有不同id
                 */
                var video_instance = videojs('video-' + index);
                //判断现在是播放还是暂停
                if($this.hasClass('glyphicon-pause')) {
                    $this.removeClass('glyphicon-pause');
                    $this.addClass('glyphicon-play');
                    video_instance.pause();
                } else {
                    $this.removeClass('glyphicon-play');
                    $this.addClass('glyphicon-pause');
                    video_instance.play();
                }
            });
            $('#datetimepicker1').datetimepicker({format: 'YYYY-MM-DD'});
            $('#datetimepicker2').datetimepicker({format: 'YYYY-MM-DD'});
        });


    </script>
</block>